import React, { lazy, Suspense } from "react";
import { withRouter, Redirect, Route, Switch } from "react-router-dom";

import MayLayout from "@/components/layout/MayLayout";

import Login from "@/pages/Login";
import Erro404 from "@/pages/Erro404";
const Home = lazy(() => import("@/pages/Home"));
const Goodsmanag = lazy(() => import("@/pages/Goodsmanage"));
const Banner = lazy(() => import("@/pages/Banner"));
const Member = lazy(() => import("@/pages/Member"));
const Redux = lazy(() => import("@/pages/redux"));

/**
 * 白名单 用来设定 未登录就可以访问的页面
 *
 */
const whiteList = ["/login", "/reg"];

/**
 * 路由列表 一个网页分为多个模块 每个模块会有几个到几十个页面，
 * 我们一般只需要判断该模块下的页面是否可以在登录前访问，
 *
 */
const routeList = [
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/",
    component: Home,
  },
  {
    path: "/goodsmanage",
    component: Goodsmanag,
  },
  {
    path: "/member",
    component: Member,
  },
  {
    path: "/banner",
    component: Banner,
  },
  {
    path: "/redux",
    component: Redux,
  },
];

/**
 *
 * @param {*判断当前token 是否合法有效} token
 * @returns
 */
function checkAuth(token) {
  // 有的特殊要求不止需要判断是否有token 还需要判断token是否合法有效
  // && token.includes('==')
  return token && token.includes("==");
}
function RouterGuard(props) {
  //step1: 通过props 获取当前用户访问的路径
  const {
    location: { pathname },
  } = props;

  // step 2:从当前路径以'/'开始截取到下一个'/'为止
  const currPath = pathname.match(/\/(\w*)/)[0];
  // console.log(currPath);

  // step 3： 从路由表取出匹配的路由对象
  const legalRoute = routeList.find((router) => {
    return router.path === currPath;
  });
  console.log(!legalRoute);

  // step 4: 非法路由 路由表中不存在对应路由时直接跳转404 或默认首页
  if (!legalRoute) {
    return <Route component={Erro404} />;
  }

  const { path, component } = legalRoute;
  // 判断是否有token  是否登录过
  if (checkAuth(window.localStorage.getItem("token"))) {
    // 如存在token  判断当前页是否是登录页 如果是 跳转主页
    // console.log(legalRoute, currPath, "已登录");
    if (pathname === "/login") {
      return <Redirect to="/" />;
    }

    // 其他页面正常跳转
    return (
      <MayLayout>
        <Suspense fallback={"loading..."}>
          <Switch>
            <Route path={path} component={component} />
          </Switch>
        </Suspense>
      </MayLayout>
    );
  } else {
    // 判断当前页面是否在白名单 是否可以不需要token 就可以直接访问
    if (whiteList.includes(pathname)) {
      return <Route path={path} component={component} />;
    }

    // 非白名单 跳转登录页
    return <Redirect to={"/login?" + pathname} />;
  }

  // return <div></div>;
}

export default withRouter(RouterGuard);
